// middleware/middleware_auth.go
package middleware

import (
	"github.com/gin-gonic/gin"
	"muziai-server/models/ctype"
	"muziai-server/service/redis"
	"muziai-server/utils/jwts"
	"muziai-server/utils/res"
)

type MiddlewareAuth struct {
	RedisService redis.RedisService
}

func (m MiddlewareAuth) MiddlewareAuth() gin.HandlerFunc {
	return func(c *gin.Context) {
		claims, err := jwts.GetClaimsByGin(c)

		if err != nil {
			res.FailWithError(c, err)
			c.Abort() // 拦截
			return
		}
		//判断在不在redis里面
		msg, ok := m.RedisService.HasLogoutToken(claims.Token)
		if ok {
			if msg == "" {
				msg = "当前token已注销"
			}
			res.FailWithMsg(c, msg)
			c.Abort()
			return
		}

		c.Set("claims", claims)
	}
}

func (m MiddlewareAuth) MiddlewareAdmin(c *gin.Context) {
	claims, err := jwts.GetClaimsByGin(c)
	if err != nil {
		res.FailWithError(c, err)
		c.Abort() // 拦截
		return
	}
	if claims.Role != ctype.AdminRole {
		res.FailWithMsg(c, "权限错误")
		c.Abort() // 拦截
		return
	}
	//判断在不在redis里面
	msg, ok := m.RedisService.HasLogoutToken(claims.Token)
	if ok {
		if msg == "" {
			msg = "当前token已注销"
		}
		res.FailWithMsg(c, msg)
		c.Abort()
		return
	}
	c.Set("claims", claims)
}
